<template>
  <div class="login-container">
    <div class="login-box">
      <div style="padding: 50px 30px; background-color: white; margin-left: 100px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.2)">
        <el-form ref="formRef" :rules="data.rules" :model="data.form" style="width: 300px">
          <div style="margin-bottom: 30px; font-size: 24px; text-align: center; color: #0742b1; font-weight: bold">欢迎登录</div>
          <el-form-item prop="username">
            <el-input size="large" v-model="data.form.username" placeholder="请输入账号" prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input show-password size="large" v-model="data.form.password" placeholder="请输入密码" prefix-icon="Lock"></el-input>
          </el-form-item>
          <el-form-item prop="role">
            <el-select v-model="data.form.role" style="width: 100%" size="large">
              <el-option value="ADMIN" label="管理员"></el-option>
              <el-option value="USER" label="用户"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="captcha">
            <div style="display: flex; align-items: center;">
              <div class="captcha-box" @click="refreshCaptcha" title="点击刷新验证码">{{ data.captchaOperation }}</div>
              <el-input size="large" v-model="data.form.captcha" placeholder="请输入验证码" style="width: 200px"></el-input>
            </div>
          </el-form-item>
          <div style="margin-bottom: 20px">
            <el-button @click="login" size="large" style="width: 100%" type="primary">登 录</el-button>
          </div>
          <div style="text-align: right">还没有账号？请 <a style="color: #0742b1; text-decoration: none" href="/register">注册</a></div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';

const router = useRouter();

const data = reactive({
  form: { 
    role: 'ADMIN',
    captcha: '' 
  },
  captchaOperation: '', // 验证码显示的算式
  captchaResult: 0,     // 验证码的正确结果
  rules: {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (parseInt(value) !== data.captchaResult) {
            callback(new Error('验证码错误'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});

// 生成随机验证码
const generateCaptcha = () => {
  // 生成两个随机数，确保结果在0-10范围内
  let num1, num2, operator, result;
  
  // 随机选择运算符（加法或减法）
  const useAddition = Math.random() > 0.5;
  
  if (useAddition) {
    // 加法：确保结果不超过10
    num1 = Math.floor(Math.random() * 6); // 0-5
    num2 = Math.floor(Math.random() * (11 - num1)); // 确保和不超过10
    operator = '+';
    result = num1 + num2;
  } else {
    // 减法：确保结果不小于0
    num1 = Math.floor(Math.random() * 11); // 0-10
    num2 = Math.floor(Math.random() * (num1 + 1)); // 确保差不小于0
    operator = '-';
    result = num1 - num2;
  }
  
  data.captchaOperation = `${num1} ${operator} ${num2} = ?`;
  data.captchaResult = result;
};

// 组件挂载时生成验证码
onMounted(() => {
  generateCaptcha();
});

// 点击验证码框时刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
  data.form.captcha = ''; // 清空输入
};

const formRef = ref();

const login = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 直接使用原始的表单数据，不再进行角色转换
      request.post('/login', data.form).then(res => {
        if (res.code === '200' && res.data) {
          // 确保返回的用户数据包含必要的字段
          if (!res.data.role || !res.data.username) {
            ElMessage.error('登录失败：用户数据不完整');
            return;
          }

          // 保存用户信息到 localStorage，将用户角色标准化为ADMIN或USER
          const userData = {
            ...res.data,
            role: res.data.role === '管理员' ? 'ADMIN' : res.data.role // 如果是管理员则转为ADMIN
          };
          
          localStorage.setItem('xm-pro-user', JSON.stringify(userData));
          ElMessage.success('登录成功');

          // 根据角色跳转到对应页面
          if (userData.role === 'ADMIN') {
            router.push('/manager/home');
          } else {
            router.push('/front/home');
          }
        } else {
          ElMessage.error(res.msg || '登录失败');
        }
      }).catch(error => {
        console.error('登录请求失败:', error);
        ElMessage.error('登录失败：网络错误');
      });
    }
  });
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  overflow: hidden;
  background-image: url("@/assets/xmjd.jpg");
  
  background-size: cover;
  background-position: 0 -50px;
}

.login-box {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  right: 0;
  position: absolute;
}

.captcha-box {
  flex: 1;
  margin-right: 10px;
  line-height: 40px;
  padding: 0 15px;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;
  user-select: none;
}

.captcha-box:hover {
  border-color: #c0c4cc;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  background-color: #eef1f6;
}

.captcha-box:active {
  background-color: #e4e8f1;
}
</style>